package uk.co.revisual.core
{
	import flash.display.DisplayObject;
	import flash.display.Stage;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	import org.puremvc.as3.multicore.interfaces.IFacade;
	import org.puremvc.as3.multicore.patterns.facade.Facade;

	public class CoreFacade extends Facade
	{
		public static const START_UP:String = "startUp";
		public static const CORE_ADDRESS_DELIMITER:String = ":";
		
		private static const ADDRESS_ERROR:String = "the address is not well formed: ";
		private static const NULL_CORE_ERROR:String = "the core does not exist: ";
		
		private var _logger:ILogger;
		
		public function CoreFacade( multicoreKey:String )
		{
			super(multicoreKey);
			_logger = Log.getLogger( multicoreKey );
		}
        
         public static function getInstance( key:String ):IFacade {
            if (instanceMap[ key ] == null ) instanceMap[ key ] = new CoreFacade( key );
            return instanceMap[ key ];
        }
        
		override public function sendNotification(noteName:String, body:Object=null, type:String=null):void{   	
        	if( toRedirect(noteName) ){
        		sendNotificationToCore(	getCoreKeyFragment(noteName), getIDFragment(noteName), body, type );
        	}else{        		
        		super.sendNotification(noteName, body, type);
        	}
        }
        

        
        private function toRedirect(address:String):Boolean{
        	var split:Array = address.split(CORE_ADDRESS_DELIMITER);
        	if( split.length > 2 )throw new Error( ADDRESS_ERROR + address );
        	return ( split.length == 2 );
        }
       
        private function getCoreKeyFragment(address:String):String{
        	var split:Array = address.split(CORE_ADDRESS_DELIMITER);
        	return split[0];
        }
        
        private function getIDFragment(address:String):String{
        	var split:Array = address.split(CORE_ADDRESS_DELIMITER);
        	return split[1];
        }
		
		protected function sendNotificationToCore( multicoreKey:String, notificationName:String, body:Object=null, type:String=null ):void 
		{
			if( hasCoreCheck( multicoreKey ) )getInstance( multicoreKey ).sendNotification(notificationName, body, type );
		}
		
		
		private function hasCoreCheck( key:String ):Boolean{
			if( hasCore( key ) ) return true;
			//throw new Error( NULL_CORE_ERROR + key );
			logger.warn("core: " + key + " does not exist")
			return false;
		}
		
		
		public function startup( view:DisplayObject, startCmd:Class ):void{
        	registerCommand( START_UP, startCmd );
        	sendNotification( START_UP, view );
        	removeCommand( START_UP );
        }
        
        public function injectStage( stage:Stage, mediatorClass:Class ):void{
        	registerMediator( new mediatorClass( stage ) );
        }
        
        public function get logger():ILogger{
			return _logger;
		}
		
		
	}
}